package database

import (
	"log"
	"os"

	"github.com/diogoxiang/smock/models"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

var DB *gorm.DB

// InitDB 初始化数据库连接
func InitDB() {
	var err error

	// 从环境变量获取数据库路径
	dbPath := os.Getenv("DB_PATH")
	if dbPath == "" {
		dbPath = "database/sqlite.db"
	}

	log.Println("Using database at:", dbPath)

	DB, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	if err != nil {
		log.Fatal("Failed to connect database:", err)
	}

	// 自动迁移数据库模型
	err = DB.AutoMigrate(
		&models.MockAPI{},
		&models.MockResponse{},
		&models.MatchRule{},
		&models.RequestLog{},
	)
	if err != nil {
		log.Fatal("Failed to migrate database:", err)
	}

	log.Println("Database initialized successfully")
}
